<?php
	/**
	*文章管理类
	**/
	class ArticleClass {
		// 构造函数
		public function __constract(){
		}

		// 获取文章列表
		public function getList($data){
			global $db;
			$pageCurrent = $data->pageCurrent;
			$pageSize = $data->pageSize;
			$catId = $data->catId;

			// 获取模型数据存储表名
			$catToTableNameItem = $this->getCatToTableName($catId);
			$tableName = $catToTableNameItem['tableName'];

			// 获取所有数据
			$sql = "select SQL_CALC_FOUND_ROWS art.id,art.title,art.pic,art.recommend,art.create_time as createTime,user.name as createName,cat.id as catId,cat.name as catName from " . $tableName . " as art left join admin_user as user on art.creator=user.id left join category as cat on art.catid=cat.id where art.catid in(" . $this->getCatAndChildrenId($catId) . ") order by art.id desc limit :start,:count";
			$db->query($sql,array(
							"start"=>($pageCurrent-1) * $pageSize,
							"count"=> $pageSize
						));
			$artList = $db->prepare->fetchAll();
			

			// 获取总条数
			$db->query("select FOUND_ROWS() as total", "");
			$total = $db->prepare->fetchAll();
		
			$data = array(
					"total"=>$total[0]['total'],
					"data"=>$artList
				);

			return $data;
		}

		// 添加文章
		public function add($data){
			global $db, $session;
			$loginUserId = $session->get("userId");
			$title = $data->title;
			$description = $data->description;
			$content = $data->content;
			$pic = $data->pic;
			$catId = $data->catId;
			$recommend = $data->recommend;

			// 获取数据存储表名称和modelid
			$catToTableNameItem = $this->getCatToTableName($catId);
			$tableName = $catToTableNameItem['tableName'];
			$modelId = $catToTableNameItem["modelId"];
			$tableNameData = $tableName . "_data";

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			// 查询文章名称是否已经存在
			$sql = "select * from " . $tableName . " where title=:title for update";
			$db->query($sql, array(
							"title"=>$title
							)
						);
			$result = $db->prepare->fetchAll();
			if($result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "文章名称已经存在了，请重新命名！", null);
			}

			// 获取模型添加的对应字段
			$db->query("select field
						from model_field
						where
							modelid=:modelId",
						array(
							"modelId"=>$modelId
							)
						);
			$fieldList = $db->prepare->fetchAll();

			// 插入一条新数据
			$len = count($fieldList);
			$val = array("title"=>$title,
						"description"=>$description,
						"pic"=>$pic,
						"catid"=>$catId,
						"recommend"=>$recommend,
						"creator"=>$loginUserId
						);
			$keys = "title,description,pic,catid,recommend,creator";
			$params = ":title,:description,:pic,:catid,:recommend,:creator";
			for($i=0; $i<$len; $i++){
				$item = $fieldList[$i];
				$keys = $keys . ',' . $item['field'];
				$params = $params . ',:' . $item['field'];
				$val[$item['field']] = $data->$item['field'];
			}
			$sql = "insert into " . $tableName . "(" . $keys . ") values(" . $params . ")";
			$db->query($sql, $val);
			$result = $db->prepare->rowCount();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "操作失败！", null);
			}

			// 查找新添加的一条数据的id
			$db->query("select last_insert_id() as id", "");
			$result = $db->prepare->fetchAll();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "操作失败！", null);
			}
			$artId = $result[0]["id"];

			// 插入一条新数据
			$sql = "insert into " . $tableNameData . "(" . ($tableName . 'id') . ",content) 
						values(:" . ($tableName . 'id') . ",:content)";
			$db->query($sql,
						array(
							"content"=>$content,
							($tableName . 'id')=>$artId,
							)
						);
			$result = $db->prepare->rowCount();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "操作失败！", null);
			}

			$db->PDO->commit();
			// 事物结束
		}

		// 删除栏目
		public function del($data){
			global $db;
			$id = $data->id;
			$catId = $data->catId;

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			// 获取数据存储主副表名称
			$catToTableNameItem = $this->getCatToTableName($catId);
			$tableName = $catToTableNameItem["tableName"];
			$tableNameData = $tableName . "_data";
			$artId = $tableName . 'id';

			// 删除副表中的数据
			$sql = "delete from " . $tableNameData . " where " . $artId . "=:id";
			$db->query($sql, array(
							"id"=>$id
							)
						);

			// 删除主表表中的数据
			$sql = "delete from " . $tableName . " where id=:id";
			$db->query($sql, array(
							"id"=>$id
							)
						);

			$db->PDO->commit();
			// 事物结束
		}

		// 编辑文章
		public function edit($data){
			global $db, $session;
			$loginUserId = $session->get("userId");
			$title = $data->title;
			$description = $data->description;
			$content = $data->content;
			$pic = $data->pic;
			$catId = $data->catId;
			$recommend = $data->recommend;
			$id = $data->id;

			// 获取数据存储表名称和modelid
			$catToTableNameItem = $this->getCatToTableName($catId);
			$modelId = $catToTableNameItem["modelId"];
			$tableName = $catToTableNameItem["tableName"];
			$tableNameData = $tableName . "_data";
			$artId = $tableName . 'id';

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			// 查询文章名称是否已经存在
			$sql = "select * from " . $tableName . " where id=:id for update";
			$db->query($sql, array(
							"id"=>$id
							)
						);
			$result = $db->prepare->fetchAll();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "id参数有误！", null);
			}

			// 获取模型添加的对应字段
			$db->query("select field
						from model_field
						where
							modelid=:modelId",
						array(
							"modelId"=>$modelId
							)
						);
			$fieldList = $db->prepare->fetchAll();

			// 更新一条新数据
			$len = count($fieldList);
			$val = array("title"=>$title,
						"description"=>$description,
						"pic"=>$pic,
						"catid"=>$catId,
						"recommend"=>$recommend,
						"id"=>$id
						);
			$params = "title=:title,description=:description,pic=:pic,catid=:catid,recommend=:recommend";
			for($i=0; $i<$len; $i++){
				$item = $fieldList[$i];
				$params = $params . ',' . $item['field'] . '=:' . $item['field'];
				$val[$item['field']] = $data->$item['field'];
			}
			$sql = "update " . $tableName . " set " . $params . " where id=:id";
			$db->query($sql, $val);
			$result = $db->prepare->rowCount();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "操作失败！", null);
			}

			// 更新一条新数据
			$sql = "update " . $tableNameData . " set content=:content where " . $artId . "=:id";
			$db->query($sql,array(
								"content"=>$content,
								"id"=>$id
							));

			$db->PDO->commit();
			// 事物结束
		}

		// 获取单条文章信息
		public function getOne($data){
			global $db;
			$id = $data->id;
			$catId = $data->catId;

			// 获取数据存储主副表名称
			$catToTableNameItem = $this->getCatToTableName($catId);
			$tableName = $catToTableNameItem["tableName"];
			$modelId = $catToTableNameItem["modelId"];
			$tableNameData = $tableName . "_data";
			$artId = $tableName . 'id';

			// 获取模型添加的对应字段
			$db->query("select field
						from model_field
						where
							modelid=:modelId",
						array(
							"modelId"=>$modelId
							)
						);
			$fieldList = $db->prepare->fetchAll();

			// 按id搜索这条数据
			$len = count($fieldList);
			$keys = "title,description,pic,catid,recommend,creator";
			for($i=0; $i<$len; $i++){
				$item = $fieldList[$i];
				$keys = $keys . ',' . $item['field'];
			}
			$sql = "select " . $keys . " from " . $tableName . " where id=:id";
			$db->query($sql, array("id"=>$id));
			$result = $db->prepare->fetchAll();
			$info = $result[0];

			// 获取content数据
			$sql = "select content from " . $tableNameData . " where $artId=:id";
			$db->query($sql, array("id"=>$id));
			$result = $db->prepare->fetchAll();
			$info["content"] = $result[0]['content'];
			return $info;
		}

		// 获取catId对应模型数据存储表名称数组
		private function getCatToTableName($catId){
			global $db, $session;
			$session->del('catToTableName');
			$catToTableName = $session->get('catToTableName');

			if($catToTableName){
				$catToTableName = unserialize($catToTableName);
			} else {
				// 获取栏目id和数据表名称数据
				$result = $this->getCatList($catId);
				
				$len = count($result);
				for($i=0; $i<$len; $i++){
					$item = $result[$i];
					$catToTableName[$item['catId']] = $item;
				}
				$session->set('catToTableName', serialize($catToTableName));
			}
			return $catToTableName[$catId];
		}

		// 获取栏目和子栏目id
		private function getCatAndChildrenId($catId){
			global $db, $session;
			$session->del('catToTableName');
			$catToTableName = $session->get('catToTableName');

			if($catToTableName){
				$catToTableName = unserialize($catToTableName);
			} else {
				// 获取栏目id和数据表名称数据
				$result = $this->getCatList($catId);
				
				$len = count($result);
				for($i=0; $i<$len; $i++){
					$item = $result[$i];
					$catToTableName[$item['catId']] = $item;
				}
				$session->set('catToTableName', serialize($catToTableName));
			}
			
			// 获取栏目和子栏目id
			$catAndChildrenId = array($catId);
			$catToTableNameArr = array();
			foreach($catToTableName as $key=>$val) {
				if($val['catId'] != $catId){
					array_push($catToTableNameArr, $val);
				}
			}

			function travData($catToTableNameArr, $catId){
				$len = count($catToTableNameArr);
				$arr = array();
				for($j=0; $j<$len; $j++){
					$item = $catToTableNameArr[$j];
					if($item['parentId'] == $catId){
						array_push($arr, $item['catId']);
						array_merge($arr, travData($catToTableNameArr, $item['catId']));
					}
				}
				return $arr;
			}

			$catAndChildrenId = array_merge($catAndChildrenId, travData($catToTableNameArr, $catId));

			return join(',', $catAndChildrenId);
		}

		// 获取栏目列表
		private function getCatList($catId){
			global $db;
			// 获取栏目id和数据表名称数据
			$db->query("select cat.id as catId,cat.parent_id as parentId, model.table_name as tableName,model.id as modelId 
						from category as cat 
						left join model 
						on cat.modelid=model.id",
						array(
							"catId"=>$catId
							));
			$result = $db->prepare->fetchAll();
			if(!$result){
				returnAjaxJson(400, "catId参数有误！", null);
			}
			return $result;
		}

	}
?>